package cn.com.elite;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.elite.algorithm.GUID;

public class GetRecord extends HttpServlet {
	private static final Log log=LogFactory.getLog(GetRecord.class);
	private cn.com.elite.FtpBean ftpbean;
    private String ip;
    private int port;
    private String username;
    private String password;
	private static String ContextPath="";
	private static String CMDcommand="";
	/**
	 * Constructor of the object.
	 */
	public GetRecord() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws Exception 
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	
	public static void main(String[] args) throws Exception{
		GetRecord e=new GetRecord();
		String documentpath="ftp://10.128.142.186/EliteMaster/2013_08_02/20130906220010_EXT72112.wav";
		String fileName1=e.getfileName1(documentpath);
		System.out.println("doGet_fileName1:"+fileName1);
		String fileName=e.getfileName(documentpath);
		System.out.println("doGet_fileName:"+fileName);
	}
	private String getCMDformat(int fileformat){
		log.debug("fileformat:"+fileformat);
		if(fileformat==11){
			return "g726_16 alawwav";			
		}else if(fileformat==1){
			return "alaw alawwav";		
		}else if(fileformat==2){
			return "ulaw ulawwav";		
		}else if(fileformat==12){
			return "dialgic6k wav";
		}else{
			return null;
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String rec_guid=request.getParameter("rec_guid");
		log.debug("rec_guid:"+rec_guid);
		String sql=" select * from record where record_GUID=?";
		Object[] params=new Object[]{rec_guid};  
		int[] types=new int[]{Types.VARCHAR}; 
		String documentpath="";
		int fileformat=0;
		try {
			List list=ftpbean.QueryPersonUseExecute(sql, types, params);
			if(list!=null&&list.size()>0){
				Map map=(Map)list.get(0);
				documentpath=util.getStr((String)map.get("documentpath"));
				log.debug("documentpath:"+documentpath);
				String DtataSourceName=ftpbean.getdatasourcename();
				log.debug("DtataSourceName:"+DtataSourceName);
    			if(DtataSourceName.contains("Oracle")){
    				BigDecimal adminflag1=(BigDecimal)map.get("fileformat");
    				fileformat=adminflag1.intValue();
    			}else if(DtataSourceName.contains("Microsoft SQL")){
    				fileformat=(Integer)map.get("fileformat");
    			}else if(DtataSourceName.contains("MySQL")){
    				fileformat=(Integer)map.get("fileformat");
    			}else{
    				log.error("no database type");
    			}
			}
		} catch (Exception e) {
			log.error(util.getERRO(e));
		}
		
		FTPClient ftp=null;
		String fileName1="";
		response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
		response.setHeader("pragma","no-cache");
		String filename_temp="";
		String file_temp1="";
		String file_temp="";
		try{
			fileName1=getfileName1(documentpath);
			log.info("doGet_fileName1:"+fileName1);
			String fileName=getfileName(documentpath);
			log.info("doGet_fileName:"+fileName);
			ftp=GetFtp(ip,port,username,password);
			response.setContentType("audio/x-wav;utf-8");
			response.setHeader("Content-disposition","inline;filename="+fileName1);
			GUID guid=new GUID();
			file_temp1=ContextPath+"/"+fileName1;
			log.debug("file_temp1:"+file_temp1);
			
			String address=this.getServletContext().getRealPath("/");
			filename_temp="temp\\"+guid.toString()+".wav";
			log.debug("address:"+address);
			file_temp=address+filename_temp;		
			
//			file_temp=ContextPath+"/"+guid.toString()+".wav";
			
			log.debug("file_temp:"+file_temp);
			File file=new File(file_temp1);
			FileOutputStream fos=new FileOutputStream(file);
			boolean flag=ftp.retrieveFile(fileName, fos);
			log.debug("flag:"+flag);
			fos.flush();
			fos.close();

			String command=CMDcommand+" "+file_temp1+" "+file_temp+" "+getCMDformat(fileformat);
			log.debug("command:"+command);
			Process process=Runtime.getRuntime().exec(command);
            int exitcode=process.waitFor();
            log.debug("exitcode:"+exitcode);
            if(exitcode==0||exitcode==1){
                log.debug("convert successfully");
            }else{
                log.debug("convert failed and return "+exitcode);
            }
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();

//			OutputStream output=response.getOutputStream();
//	        InputStream in=new FileInputStream(new File(file_temp));
//	        BufferedInputStream bis=new BufferedInputStream(in);//输入缓冲流
//	        BufferedOutputStream bos=new BufferedOutputStream(output);//输出缓冲流
//	        byte data[]=new byte[1024];//缓冲字节数
//	        int size=0;
//	        size=bis.read(data);
//	        while(size!=-1){
//	            bos.write(data,0,size);
//	            size=bis.read(data);
//	        }
//	        bis.close();
//	        bos.flush();//清空输出缓冲流
//	        bos.close();
//	        output.close();
		}catch(Exception e){
			log.error("doGet过程错误");
			log.error(util.getERRO(e));	
		}finally{
			ftp.disconnect();
			response.sendRedirect(filename_temp); 
			log.info("返回完成,FTP关闭");
//			log.debug("删除临时文件："+file_temp+":"+delete(file_temp));
//			log.debug("删除临时文件："+file_temp+":"+delete(file_temp1));
		}
	}
	private boolean delete(String fileName){     
        File file = new File(fileName);     
        if(!file.exists()){     
            System.out.println("删除文件失败："+fileName+"文件不存在");     
            return false;     
        }else{     
            if(file.isFile()){                         
                return deleteFile(fileName);     
            }else{    
            	return false;  
            }
        }     
    } 
	private boolean deleteFile(String fileName){     
        File file = new File(fileName);     
        if(file.isFile() && file.exists()){     
            file.delete();     
            System.out.println("删除单个文件"+fileName+"成功！");     
            return true;     
        }else{     
            System.out.println("删除单个文件"+fileName+"失败！");     
            return false;     
        }     
    }
	private String getip(String FtpURL) throws Exception{
		String ip=FtpURL;
		ip=ip.replaceAll(".*?((\\d{0,3}\\.){3}\\d{0,3}).*","$1");
		return ip;	
	}
	private String getfileName(String FtpURL) throws Exception{
		String fileName="";
		String FtpURL1=FtpURL.replace("//","");
		fileName=FtpURL1.substring(FtpURL1.indexOf("/"),FtpURL1.length());
		return fileName;
	}
	private String getfileName1(String FtpURL) throws Exception{
		String fileName="";
		fileName=FtpURL.substring(FtpURL.lastIndexOf("/")+1,FtpURL.length());
		return fileName;
	}
	
	private FTPClient GetFtp(String host,int port,String username,String password){
		FTPClient ftp=new FTPClient();
		try{
			ftp.connect(host, port); 
//			ftp.setControlEncoding("GBK");
//			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
//			conf.setServerLanguageCode("zh");			
			ftp.login(username, password);
			return ftp;
		}catch(Exception e){
			log.error("FTP获取失败");
			log.error(util.getERRO(e));
			return null;
		}
	}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		try{
	        ServletContext application;   
	        WebApplicationContext wac;   
	        application = getServletContext();   
	        wac = WebApplicationContextUtils.getWebApplicationContext(application);//获取spring的context  
	        ftpbean = (cn.com.elite.FtpBean) wac.getBean("ftpbean"); 
	        
			ContextPath=this.getInitParameter("ContextPath");
			log.info("ContextPath:"+ContextPath);
			CMDcommand=this.getInitParameter("CMDcommand");
			log.info("CMDcommand:"+CMDcommand);
			username=this.getInitParameter("username");
			log.info("username:"+username);
			password=this.getInitParameter("password");
			log.info("password:"+password);
			String port1=this.getInitParameter("port");
			port=Integer.parseInt(port1);
			log.info("port:"+port);
			ip=this.getInitParameter("ip");
			log.info("ip:"+ip);
		}catch(Exception e){
			log.info(util.getERRO(e));
		}
	}

}
